﻿using System.Drawing;
using System.IO;

namespace WebPages.Bll
{
    public class GraphicUtilities
    {
        public Stream CreateThumbnail(Stream input)
        {
            var orig = new Bitmap(input);
            int width;
            int height;

            if (orig.Width > orig.Height)
            {
                width = 64;
                height = 64 * orig.Height / orig.Width;
            }
            else
            {
                height = 64;
                width = 64 * orig.Width / orig.Height;
            }

            var thumbnailImage = new Bitmap(width, height);

            using (var graphic = Graphics.FromImage(thumbnailImage))
            {
                graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                graphic.DrawImage(orig, 0, 0, width, height);
                var stream = new MemoryStream();
                thumbnailImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                stream.Seek(0, SeekOrigin.Begin);
                return stream;
            }
        }
    }
}